package net.toocruel.iqismart.web.controller.base;

import net.toocruel.iqismart.dao.AreaRepository;
import net.toocruel.iqismart.entity.common.Area;
import net.toocruel.iqismart.entity.constants.Gender;
import net.toocruel.iqismart.entity.rbac.User;
import net.toocruel.iqismart.entity.setting.Setting;
import net.toocruel.iqismart.service.ResourceService;
import net.toocruel.iqismart.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Auther sty
 * @createTime 2018/4/28 下午5:51
 */
public abstract class AbstractBaseController {

    @Autowired
    private ResourceService resourceService;

    @Autowired
    private UserService userService;

    protected Map<String,Object> errs = new HashMap<>();

    /**
     * 返回模块名 对应classpath:resources/templates/themes/主题目录/ 下面的目录
     * @return
     */
    protected String getModule(){
        return "";
    }

    /**
     * 返回模板绝地路径
     * @param name
     * @return
     */
    protected String getTemplate(String name) {
        if(StringUtils.isBlank(getModule())){
            return StringUtils.join("/themes/",Setting.SETTING.getWebsite().getTheme(),"/",name);
        }
        return StringUtils.join("/themes/",Setting.SETTING.getWebsite().getTheme(),"/",getModule()+"/"+name);
    }

    protected String getTemplate(String module,String name) {
        return StringUtils.join("/themes/",Setting.SETTING.getWebsite().getTheme(),"/",module+"/"+name);
    }



    @ModelAttribute("seoTitle")
    public String seoTitle(HttpServletRequest request){
        return "";
    }

    /**
     * 将当前登录用户放入每个请求的request中
     * @param request
     * @param session
     * @return
     */
    @ModelAttribute("currentUser")
    public User getCurrentUser(HttpServletRequest request, HttpSession session){
        User currentUser = null;
        if(session.getAttribute("currentUser") == null){
            SecurityContext ctx = SecurityContextHolder.getContext();
            Authentication auth = ctx.getAuthentication();
            if(auth!=null && auth.getPrincipal() instanceof User){
                User user = (User) auth.getPrincipal();
                currentUser = userService.getById(user.getId());
                session.setAttribute("currentUser",currentUser);
            }
        }else{
            currentUser = (User) session.getAttribute("currentUser");
        }



        return currentUser;
    }

    protected User getCurrentUser(){
        User currentUser = null;

        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();

        if(session.getAttribute("currentUser") == null){

        }else{
            currentUser = (User) session.getAttribute("currentUser");
        }

        return currentUser;
    }


    protected void refreshCurrentUser(){
        User currentUser = getCurrentUser();
        if(currentUser == null) return;
        currentUser = userService.getById(currentUser.getId());

        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();

        session.setAttribute("currentUser",currentUser);
    }

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private PasswordEncoder passwordEncoder;
    protected void login(String username,String password){
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

        User user = userService.getByUsername(username);
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
        token.setDetails(user);
        Authentication authenticate = authenticationManager.authenticate(token);

        SecurityContextHolder.getContext().setAuthentication(authenticate);
        request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
        HttpSession session = request.getSession();
        session.setAttribute("currentUser", user);
    }

    protected void addError(String key,String value){
        errs.put(key,value);
    }

    @Autowired
    private AreaRepository areaRepository;
    @ModelAttribute("AllProvince")
    public List<Area> createAllArea() {
        return areaRepository.findAreaByParent(null);
    }

    @ModelAttribute("AllUserGender")
    public Gender[] createAllUserGender() {
        return Gender.values();
    }


}
